﻿using System;

namespace Common
{
    /// <summary>
    /// ParseUtil 的摘要说明
    /// </summary>
    public class ParseUtil
    {
        public static int StringToInt(string str)
        {
            try
            {
                return int.Parse(str);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.StringToInt(string str)", ex);
            }
            return 0;
        }

        public static decimal StringToDecimal(string str)
        {
            try
            {
                return decimal.Parse(str);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.StringToDecimal(string str)", ex);
            }
            return 0;
        }

        /// <summary>
        /// 如果字符不是正确的日期格式将返回当前时间
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime StringToDateTime(string str)
        {
            try
            {
                return DateTime.Parse(str);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.StringToDateTime(string str)", ex);
            }
            return DateTime.Now;
        }

        public static string DateTimeToString(DateTime? dateTime)
        {
            return DateTimeToString(dateTime, "yyyy-MM-dd");
        }

        public static string DateTimeToString(DateTime? dateTime, string format)
        {
            try
            {
                if (dateTime != null)
                {
                    var dt = (DateTime) dateTime;
                    return dt.ToString(format);
                }
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.DateTimeToString(DateTime? dateTime, string format)", ex);
            }
            return "";
        }

        public static double StringToDouble(string str)
        {
            try
            {
                return double.Parse(str);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.StringToDouble(string str)", ex);
            }
            return 0;
        }

        public static float StringToFloat(string str)
        {
            try
            {
                return float.Parse(str);
            }
            catch (Exception ex)
            {
                Log.LogHandler.LogError("Common.ParseUtil.StringToFloat(string str)", ex);
            }
            return 0;
        }
    }
}